'use client';

import React, { useState, useEffect, useCallback, useMemo } from 'react';
import {
  Select,
  Button,
  Space,
  Typography,
  Card,
  TimePicker,
  Checkbox,
  Radio,
  message,
} from 'antd';
import { LeftOutlined, RightOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
import { RoleType, InstrumentSchedule, InstrumentScheduleGroup, InstrumentScheduleTimeslot, InstrumentScheduleSpecificDate, DateType, IsWorkday } from '@/types/instrument';
import { ScheduleType } from '@/types/system';
import CardView from './CardView';
import CalendarView from './CalendarView';

const { Option } = Select;
const { Text } = Typography;

// 组件模式枚举
export enum ScheduleMode {
  REGULAR = 'regular', // 普通排期模式
  SPECIFIC_DATE = 'specific_date' // 特定日期排期模式
}

// 视图模式枚举
export enum ViewMode {
  CARD = 'card', // 卡片模式（原有模式）
  CALENDAR = 'calendar' // 日历模式（新增拖拽模式）
}

// 日期状态接口
interface DayStatus {
  date: string;
  scheduleType: ScheduleType; // 1=节假日 2=调休日 3=正常周末
  isWorkday: boolean; // 是否为工作日
}

export type DisplayForType = RoleType | 'all';
export type InstrumentScheduleAll = Omit<InstrumentSchedule, 'roleType'> & { roleType: DisplayForType };

export interface WeeklyTimeSelectorProps {
  /** 组件模式 */
  mode: ScheduleMode;
  /** 视图模式 */
  viewMode?: ViewMode;
  /** 是否只读 */
  readOnly?: boolean;
  /** 最小预约时长（分钟） */
  minDuration?: number;
  /** 当前用户级别 */
  currentUserLevel?: RoleType;
  /** 普通排期数据 */
  scheduleData?: InstrumentSchedule[];
  /** 特定日期排期数据 */
  specificDateData?: InstrumentScheduleSpecificDate[];
  /** 普通排期变化回调 */
  onScheduleChange?: (schedules: InstrumentSchedule[]) => void;
  /** 特定日期排期变化回调 */
  onSpecificDateChange?: (specificDates: InstrumentScheduleSpecificDate[]) => void;
  /** 日期状态查询回调 */
  onQueryDayStatus?: (startDate: string, endDate: string) => Promise<DayStatus[]>;
  /** 已有预约数据 */
  existingBookings?: Array<{
    id: string;
    date: string;
    startTime: string;
    endTime: string;
    userName: string;
    userPhone: string;
    status: string;
  }>;
  /** 预约点击回调 */
  onBookingClick?: (bookingId: string) => void;
}

const WeeklyTimeSelector: React.FC<WeeklyTimeSelectorProps> = ({
  mode,
  viewMode = ViewMode.CARD,
  readOnly = false,
  minDuration = 30,
  currentUserLevel = RoleType.LEVEL_1_USER,
  scheduleData = [],
  specificDateData = [],
  onScheduleChange,
  onSpecificDateChange,
  onQueryDayStatus,
  existingBookings = [],
  onBookingClick
}) => {
  const [currentWeek, setCurrentWeek] = useState<Dayjs>(dayjs().startOf('week'));
  
  // 根据模式设置不同的默认用户级别
  const [displayFor, setDisplayFor] = useState<DisplayForType>(
    mode === ScheduleMode.REGULAR ? RoleType.LEVEL_1_USER : 'all'
  );

  // 当模式变化时，自动切换用户级别
  useEffect(() => {
    if (mode === ScheduleMode.REGULAR) {
      setDisplayFor(RoleType.LEVEL_1_USER);
    } else {
      setDisplayFor('all');
    }
  }, [mode]);

  const safeDisplayFor = displayFor === 'all' ? RoleType.LEVEL_1_USER : displayFor;

  // 用户级别选项
  const userLevelOptions: Array<{ label: string; value: DisplayForType }> = [
    { label: '所有用户', value: 'all' },
    { label: '1级用户', value: RoleType.LEVEL_1_USER },
    { label: '2级用户', value: RoleType.LEVEL_2_USER },
    { label: '3级用户', value: RoleType.LEVEL_3_USER },
  ];

  // RegularScheduleComponent 专用的用户级别选项（不包含"所有用户"）
  const regularUserLevelOptions: Array<{ label: string; value: RoleType }> = [
    { label: '1级用户', value: RoleType.LEVEL_1_USER },
    { label: '2级用户', value: RoleType.LEVEL_2_USER },
    { label: '3级用户', value: RoleType.LEVEL_3_USER },
  ];

  // 根据最小预约时长生成时间选项
  const generateTimeOptions = useCallback(() => {
    const options: string[] = [];
    // 如果最小时长>=30分钟，使用30分钟间隔；否则使用15分钟间隔
    const interval = minDuration >= 30 ? 30 : 15;

    for (let hour = 0; hour < 24; hour++) {
      for (let minute = 0; minute < 60; minute += interval) {
        const time = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:00`;
        options.push(time);
      }
    }
    return options;
  }, [minDuration]);

  // 选择"所有用户"时，合并所有用户级别的预约时间
  const isAllUserMode = displayFor === 'all';

  // 合并所有用户的默认排期
  const mergedScheduleData: InstrumentScheduleAll[] = useMemo(() => {
    if (!isAllUserMode) return scheduleData as InstrumentScheduleAll[];
    
    // 保持原始的分组结构，但合并所有用户级别的数据
    const allGroups: InstrumentScheduleGroup[] = [];
    
    (scheduleData || []).forEach(sch => {
      sch.groups.forEach(group => {
        // 检查是否已存在相同配置的组
        const existingGroup = allGroups.find(g => 
          g.isWorkday === group.isWorkday && 
          g.unfixDays === group.unfixDays
        );
        
        if (existingGroup) {
          // 合并时间段
          existingGroup.timeslots.push(...group.timeslots);
        } else {
          // 添加新组
          allGroups.push({
            isWorkday: group.isWorkday,
            unfixDays: group.unfixDays,
            timeslots: [...group.timeslots]
          });
        }
      });
    });
    
    return [{ roleType: 'all', groups: allGroups }];
  }, [isAllUserMode, scheduleData]);

  // 合并所有用户的特定日期排期
  const mergedSpecificDates = useMemo(() => {
    if (!isAllUserMode) return specificDateData;
    
    // 按日期分组，合并所有用户级别的特定日期配置
    const dateMap = new Map<string, InstrumentScheduleSpecificDate>();
    
    (specificDateData || []).forEach(item => {
      if (!dateMap.has(item.specificDate)) {
        // 创建新的日期配置
        dateMap.set(item.specificDate, {
          roleType: 'all' as unknown as RoleType,
          specificDate: item.specificDate,
          dateType: item.dateType,
          timeslots: [...item.timeslots]
        });
      } else {
        // 合并到现有配置
        const existing = dateMap.get(item.specificDate)!;
        
        // 合并时间段
        if (item.dateType === DateType.CUSTOM_TIME_SLOTS) {
          existing.timeslots.push(...item.timeslots);
        }
        
        // 如果有任何一个配置是关闭整天，则整体显示为关闭整天
        if (item.dateType === DateType.CLOSE_ALL_DAY) {
          existing.dateType = DateType.CLOSE_ALL_DAY;
          existing.timeslots = [];
        }
      }
    });
    
    return Array.from(dateMap.values());
  }, [isAllUserMode, specificDateData]);

  if (mode === ScheduleMode.REGULAR) {
    return <RegularScheduleComponent 
      readOnly={readOnly}
      minDuration={minDuration}
      currentUserLevel={currentUserLevel}
      scheduleData={mergedScheduleData}
      onScheduleChange={onScheduleChange as (schedules: InstrumentScheduleAll[]) => void}
      displayFor={safeDisplayFor}
      onDisplayChange={setDisplayFor as (level: RoleType) => void}
      userLevelOptions={regularUserLevelOptions}
      generateTimeOptions={generateTimeOptions}
    />;
  }

  return <SpecificDateScheduleComponent 
    readOnly={isAllUserMode || readOnly}
    minDuration={minDuration}
    currentUserLevel={currentUserLevel}
    specificDateData={mergedSpecificDates}
    scheduleData={mergedScheduleData}
    onSpecificDateChange={onSpecificDateChange}
    onQueryDayStatus={onQueryDayStatus}
    existingBookings={existingBookings}
    onBookingClick={onBookingClick}
    currentWeek={currentWeek}
    onWeekChange={setCurrentWeek}
    displayFor={displayFor}
    onDisplayChange={setDisplayFor as (level: DisplayForType) => void}
    userLevelOptions={userLevelOptions}
    generateTimeOptions={generateTimeOptions}
    viewMode={viewMode}
  />;
};

// 普通排期组件
const RegularScheduleComponent: React.FC<{
  readOnly: boolean;
  minDuration: number;
  currentUserLevel: RoleType;
  scheduleData: InstrumentScheduleAll[];
  onScheduleChange?: (schedules: InstrumentScheduleAll[]) => void;
  displayFor: RoleType;
  onDisplayChange: (level: RoleType) => void;
  userLevelOptions: Array<{ label: string; value: RoleType }>;
  generateTimeOptions: () => string[];
}> = ({ 
  readOnly, 
  scheduleData, 
  onScheduleChange,
  displayFor,
  onDisplayChange,
  userLevelOptions,
}) => {
  const [schedules, setSchedules] = useState<InstrumentScheduleAll[]>(scheduleData);

  useEffect(() => {
    setSchedules(scheduleData);
  }, [scheduleData]);

  // 获取当前显示用户级别的排期
  const currentSchedule = schedules.find(s => s.roleType === displayFor);

  // 添加新的时间组
  const handleAddGroup = () => {
    const newGroup: InstrumentScheduleGroup = {
      isWorkday: IsWorkday.YES,
      unfixDays: '',
      timeslots: []
    };

    const updatedSchedules = [...schedules];
    const scheduleIndex = updatedSchedules.findIndex(s => s.roleType === displayFor);
    
    if (scheduleIndex >= 0) {
      updatedSchedules[scheduleIndex].groups.push(newGroup);
    } else {
      updatedSchedules.push({
        roleType: displayFor,
        groups: [newGroup]
      });
    }
    
    setSchedules(updatedSchedules);
    onScheduleChange?.(updatedSchedules);
  };

  // 更新时间组
  const handleUpdateGroup = (groupIndex: number, field: string, value: unknown) => {
    const updatedSchedules = [...schedules];
    const scheduleIndex = updatedSchedules.findIndex(s => s.roleType === displayFor);
    
    if (scheduleIndex >= 0) {
      updatedSchedules[scheduleIndex].groups[groupIndex] = {
        ...updatedSchedules[scheduleIndex].groups[groupIndex],
        [field]: value
      };
      setSchedules(updatedSchedules);
      onScheduleChange?.(updatedSchedules);
    }
  };

  // 删除时间组
  const handleDeleteGroup = (groupIndex: number) => {
    const updatedSchedules = [...schedules];
    const scheduleIndex = updatedSchedules.findIndex(s => s.roleType === displayFor);
    
    if (scheduleIndex >= 0) {
      updatedSchedules[scheduleIndex].groups.splice(groupIndex, 1);
      setSchedules(updatedSchedules);
      onScheduleChange?.(updatedSchedules);
    }
  };

  // 添加时间段
  const handleAddTimeslot = (groupIndex: number) => {
    const newTimeslot: InstrumentScheduleTimeslot = {
      startTime: '09:00:00',
      endTime: '17:00:00'
    };

    const updatedSchedules = [...schedules];
    const scheduleIndex = updatedSchedules.findIndex(s => s.roleType === displayFor);
    
    if (scheduleIndex >= 0) {
      updatedSchedules[scheduleIndex].groups[groupIndex].timeslots.push(newTimeslot);
      setSchedules(updatedSchedules);
      onScheduleChange?.(updatedSchedules);
    }
  };

  // 时间字符串转分钟数
  const timeStringToMinutes = (timeStr: string): number => {
    const [hours, minutes] = timeStr.split(':').map(Number);
    return hours * 60 + minutes;
  };

  // 校验时间段是否符合最小间隔要求
  const validateTimeSlotInterval = (startTime: string, endTime: string): boolean => {
    const startMinutes = timeStringToMinutes(startTime);
    const endMinutes = timeStringToMinutes(endTime);
    const duration = endMinutes - startMinutes;

    // 检查时长是否满足最小要求
    if (duration < minDuration) {
      message.error(`时间段长度不能少于${minDuration}分钟`);
      return false;
    }

    // 如果设置了30分钟最小间隔，检查时间点是否符合要求
    if (minDuration >= 30) {
      // 检查开始时间是否为30分钟的倍数
      if (startMinutes % 30 !== 0) {
        const nextValidStart = Math.ceil(startMinutes / 30) * 30;
        const nextValidStartHour = Math.floor(nextValidStart / 60);
        const nextValidStartMin = nextValidStart % 60;
        const nextValidStartTime = `${nextValidStartHour.toString().padStart(2, '0')}:${nextValidStartMin.toString().padStart(2, '0')}`;
        message.error(`开始时间必须为30分钟的倍数，建议调整为${nextValidStartTime}`);
        return false;
      }

      // 检查结束时间是否为30分钟的倍数
      if (endMinutes % 30 !== 0) {
        const nextValidEnd = Math.ceil(endMinutes / 30) * 30;
        const nextValidEndHour = Math.floor(nextValidEnd / 60);
        const nextValidEndMin = nextValidEnd % 60;
        const nextValidEndTime = `${nextValidEndHour.toString().padStart(2, '0')}:${nextValidEndMin.toString().padStart(2, '0')}`;
        message.error(`结束时间必须为30分钟的倍数，建议调整为${nextValidEndTime}`);
        return false;
      }

      // 检查时长是否为30分钟的倍数
      if (duration % 30 !== 0) {
        message.error(`时间段长度必须为30分钟的倍数`);
        return false;
      }
    }

    return true;
  };

  // 获取TimePicker的分钟步长
  const getMinuteStep = () => {
    // 如果最小时长>=30分钟，使用30分钟步长；否则使用15分钟步长
    return minDuration >= 30 ? 30 : 15;
  };

  // 更新时间段
  const handleUpdateTimeslot = (groupIndex: number, timeslotIndex: number, field: string, value: string) => {
    const updatedSchedules = [...schedules];
    const scheduleIndex = updatedSchedules.findIndex(s => s.roleType === displayFor);

    if (scheduleIndex >= 0) {
      const currentTimeslot = updatedSchedules[scheduleIndex].groups[groupIndex].timeslots[timeslotIndex];
      const newTimeslot = {
        ...currentTimeslot,
        [field]: value
      };

      // 校验时间段
      if (!validateTimeSlotInterval(newTimeslot.startTime, newTimeslot.endTime)) {
        return; // 校验失败，不更新
      }

      updatedSchedules[scheduleIndex].groups[groupIndex].timeslots[timeslotIndex] = newTimeslot;
      setSchedules(updatedSchedules);
      onScheduleChange?.(updatedSchedules);
    }
  };

  // 删除时间段
  const handleDeleteTimeslot = (groupIndex: number, timeslotIndex: number) => {
    const updatedSchedules = [...schedules];
    const scheduleIndex = updatedSchedules.findIndex(s => s.roleType === displayFor);
    
    if (scheduleIndex >= 0) {
      updatedSchedules[scheduleIndex].groups[groupIndex].timeslots.splice(timeslotIndex, 1);
      setSchedules(updatedSchedules);
      onScheduleChange?.(updatedSchedules);
    }
  };

  return (
    <div>
      {/* 用户级别选择 */}
      <div style={{ marginBottom: 16, display: 'flex', alignItems: 'center', gap: 16 }}>
        <Text strong>设置用户级别：</Text>
        <Select 
          value={displayFor}
          onChange={onDisplayChange}
          style={{ width: 120 }}
          disabled={readOnly}
        >
          {userLevelOptions.map(option => (
            <Option key={option.value} value={option.value}>
              {option.label}
            </Option>
          ))}
        </Select>
      </div>

      {/* 默认可预约时间配置 */}
      <Card 
        title={`${userLevelOptions.find(o => o.value === displayFor)?.label}默认可预约时间`}
        extra={
          !readOnly && (
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={handleAddGroup}
            >
              添加时间组
            </Button>
          )
        }
      >
        {currentSchedule?.groups.map((group, groupIndex) => (
          <Card 
            key={groupIndex}
            type="inner" 
            title={`时间组 ${groupIndex + 1}`}
            extra={
              !readOnly && (
                <Button 
                  type="link" 
                  icon={<DeleteOutlined />}
                  onClick={() => handleDeleteGroup(groupIndex)}
                >
                  删除
                </Button>
              )
            }
            style={{ marginBottom: 16 }}
          >
            {/* 日期类型选择 */}
            <div style={{ marginBottom: 16 }}>
              <Text strong>日期类型：</Text>
              <Radio.Group 
                value={group.isWorkday} 
                onChange={(e) => handleUpdateGroup(groupIndex, 'isWorkday', e.target.value)}
                disabled={readOnly}
              >
                <Radio value={IsWorkday.YES}>法定工作日（智能过滤节假日）</Radio>
                <Radio value={IsWorkday.NO}>自定义星期</Radio>
              </Radio.Group>
            </div>

            {/* 自定义星期选择 */}
            {group.isWorkday === 0 && (
              <div style={{ marginBottom: 16 }}>
                <Text strong>选择星期：</Text>
                <Checkbox.Group 
                  value={group.unfixDays ? group.unfixDays.split(',').map(Number) : []}
                  onChange={(values) => handleUpdateGroup(groupIndex, 'unfixDays', values.join(','))}
                  disabled={readOnly}
                >
                  <Checkbox value={1}>周一</Checkbox>
                  <Checkbox value={2}>周二</Checkbox>
                  <Checkbox value={3}>周三</Checkbox>
                  <Checkbox value={4}>周四</Checkbox>
                  <Checkbox value={5}>周五</Checkbox>
                  <Checkbox value={6}>周六</Checkbox>
                  <Checkbox value={7}>周日</Checkbox>
                </Checkbox.Group>
              </div>
            )}

            {/* 时间段配置 */}
            <div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
                <Text strong>时间段：</Text>
                {!readOnly && (
                  <Button 
                    type="dashed" 
                    size="small"
                    icon={<PlusOutlined />}
                    onClick={() => handleAddTimeslot(groupIndex)}
                  >
                    添加时间段
                  </Button>
                )}
              </div>
              
              {group.timeslots.map((timeslot, timeslotIndex) => (
                <div key={timeslotIndex} style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                  <TimePicker
                    value={timeslot.startTime ? dayjs(timeslot.startTime, 'HH:mm:ss') : null}
                    format="HH:mm"
                    placeholder="开始时间"
                    disabled={readOnly}
                    minuteStep={getMinuteStep()}
                    onChange={(time) =>
                      handleUpdateTimeslot(groupIndex, timeslotIndex, 'startTime', time ? time.format('HH:mm:ss') : '09:00:00')
                    }
                  />
                  <Text>至</Text>
                  <TimePicker
                    value={timeslot.endTime ? dayjs(timeslot.endTime, 'HH:mm:ss') : null}
                    format="HH:mm"
                    placeholder="结束时间"
                    disabled={readOnly}
                    minuteStep={getMinuteStep()}
                    onChange={(time) =>
                      handleUpdateTimeslot(groupIndex, timeslotIndex, 'endTime', time ? time.format('HH:mm:ss') : '17:00:00')
                    }
                  />
                  {!readOnly && (
                    <Button 
                      type="link" 
                      icon={<DeleteOutlined />}
                      onClick={() => handleDeleteTimeslot(groupIndex, timeslotIndex)}
                    >
                      删除
                    </Button>
                  )}
                </div>
              ))}
            </div>
          </Card>
        ))}

        {(!currentSchedule || currentSchedule.groups.length === 0) && (
          <div style={{ textAlign: 'center', padding: 32, color: '#999' }}>
            暂无时间配置，点击&quot;添加时间组&quot;开始配置
          </div>
        )}
      </Card>
    </div>
  );
};

// 特定日期排期组件
const SpecificDateScheduleComponent: React.FC<{
  readOnly: boolean;
  minDuration: number;
  currentUserLevel: RoleType;
  specificDateData: InstrumentScheduleSpecificDate[];
  scheduleData: InstrumentScheduleAll[];
  onSpecificDateChange?: (specificDates: InstrumentScheduleSpecificDate[]) => void;
  onQueryDayStatus?: (startDate: string, endDate: string) => Promise<DayStatus[]>;
  existingBookings: Array<{
    id: string;
    date: string;
    startTime: string;
    endTime: string;
    userName: string;
    userPhone: string;
    status: string;
  }>;
  onBookingClick?: (bookingId: string) => void;
  currentWeek: Dayjs;
  onWeekChange: (week: Dayjs) => void;
  displayFor: DisplayForType;
  onDisplayChange: (level: DisplayForType) => void;
  userLevelOptions: Array<{ label: string; value: DisplayForType }>;
  generateTimeOptions: () => string[];
  viewMode?: ViewMode;
}> = ({ 
  readOnly, 
  minDuration,
  specificDateData, 
  scheduleData,
  onSpecificDateChange,
  onQueryDayStatus,
  currentWeek,
  onWeekChange,
  displayFor,
  onDisplayChange,
  userLevelOptions,
  viewMode = ViewMode.CARD,
}) => {
  const [specificDates, setSpecificDates] = useState<InstrumentScheduleSpecificDate[]>(specificDateData);
  const [selectedDate, setSelectedDate] = useState<string>('');
  const [dayStatusMap, setDayStatusMap] = useState<Map<string, DayStatus>>(new Map());

  // const safeDisplayFor = displayFor === 'all' ? RoleType.LEVEL_1_USER : displayFor;

  useEffect(() => {
    setSpecificDates(specificDateData);
  }, [specificDateData]);

  // 查询当周日期状态
  useEffect(() => {
    const queryWeekStatus = async () => {
      if (onQueryDayStatus) {
        const startDate = currentWeek.format('YYYY-MM-DD');
        const endDate = currentWeek.add(6, 'day').format('YYYY-MM-DD');
        
        try {
          const dayStatuses = await onQueryDayStatus(startDate, endDate);
          const statusMap = new Map<string, DayStatus>();
          dayStatuses.forEach(status => {
            statusMap.set(status.date, status);
          });
          setDayStatusMap(statusMap);
        } catch (error) {
          console.error('查询日期状态失败:', error);
        }
      }
    };

    queryWeekStatus();
  }, [currentWeek, onQueryDayStatus]);

  // 根据日期和默认配置生成时间段
  const generateDefaultTimeslots = (date: string): InstrumentScheduleTimeslot[] => {
    const dayStatus = dayStatusMap.get(date);
    
    if (displayFor === 'all') {
      // 合并所有用户级别的默认时间段
      const allTimeslots: InstrumentScheduleTimeslot[] = [];
      
      // 处理默认排期数据
      scheduleData.forEach(schedule => {
        if (!schedule) return;
        
        // 根据日期状态匹配对应的时间组
        for (const group of schedule.groups) {
          let shouldInclude = false;
          
          if (group.isWorkday === IsWorkday.YES) {
            // 法定工作日配置
            if (dayStatus && dayStatus.isWorkday) {
              shouldInclude = true;
            }
          } else if (group.isWorkday === IsWorkday.NO && group.unfixDays) {
            // 自定义星期配置
            const allowedDays = group.unfixDays.split(',').map(Number);
            const dayOfWeek = dayjs(date).day() === 0 ? 7 : dayjs(date).day(); // 转换为周一=1的格式
            
            if (allowedDays.includes(dayOfWeek)) {
              shouldInclude = true;
            }
          }
          
          if (shouldInclude) {
            allTimeslots.push(...group.timeslots);
          }
        }
      });
      
      return allTimeslots;
    }
    
    const defaultSchedule = scheduleData.find(s => s.roleType === displayFor);
    
    if (!defaultSchedule || !dayStatus) {
      return [];
    }

    // 根据日期状态匹配对应的时间组
    for (const group of defaultSchedule.groups) {
      if (group.isWorkday === IsWorkday.YES && dayStatus.isWorkday) {
        // 法定工作日
        return group.timeslots;
      } else if (group.isWorkday === IsWorkday.NO && group.unfixDays) {
        // 自定义星期
        const allowedDays = group.unfixDays.split(',').map(Number);
        const dayOfWeek = dayjs(date).day() === 0 ? 7 : dayjs(date).day(); // 转换为周一=1的格式
        
        if (allowedDays.includes(dayOfWeek)) {
          return group.timeslots;
        }
      }
    }

    return [];
  };

  // 将默认时间段转换为特定日期时间段格式
  const convertToSpecificTimeslots = (timeslots: InstrumentScheduleTimeslot[]) => {
    return timeslots.map(slot => ({
      startTime: slot.startTime,
      endTime: slot.endTime
    }));
  };

  // 切换到上一周
  const handlePrevWeek = () => {
    const newWeek = currentWeek.subtract(1, 'week');
    onWeekChange(newWeek);
  };

  // 切换到下一周
  const handleNextWeek = () => {
    const newWeek = currentWeek.add(1, 'week');
    onWeekChange(newWeek);
  };

  // 生成本周日期
  const weekDates = useMemo(() => {
    const dates = [];
    for (let i = 0; i < 7; i++) {
      const date = currentWeek.add(i, 'day');
      dates.push({
        date: date.format('YYYY-MM-DD'),
        dayName: ['日', '一', '二', '三', '四', '五', '六'][date.day()],
        dayNumber: date.date(),
        dayObj: date
      });
    }
    return dates;
  }, [currentWeek]);

  // 获取特定日期的配置
  const getSpecificDateConfig = (date: string) => {
    if (displayFor === 'all') {
      // 合并所有用户级别的特定日期配置
      const allConfigs = specificDates.filter(sd => sd.specificDate === date);
      
      // 获取所有用户级别的默认时间段
      const defaultTimeslots = generateDefaultTimeslots(date);
      
      if (allConfigs.length === 0) {
        // 如果没有特定配置，但有默认配置，返回默认配置
        if (defaultTimeslots.length > 0) {
          return {
            roleType: 'all' as unknown as RoleType,
            specificDate: date,
            dateType: DateType.CUSTOM_TIME_SLOTS,
            timeslots: convertToSpecificTimeslots(defaultTimeslots),
            // 标记这些是默认时间段
            isDefaultOnly: true
          };
        }
        return undefined;
      }
      
      // 合并所有配置的时间段
      const allTimeslots: Array<{ startTime: string; endTime: string }> = [];
      let hasCloseAllDay = false;
      
      // 先添加默认时间段
      allTimeslots.push(...convertToSpecificTimeslots(defaultTimeslots));
      
      // 再添加特定日期配置的时间段
      allConfigs.forEach(config => {
        if (config.dateType === DateType.CUSTOM_TIME_SLOTS) {
          allTimeslots.push(...config.timeslots);
        } else if (config.dateType === DateType.CLOSE_ALL_DAY) {
          hasCloseAllDay = true;
        }
      });
      
      // 返回合并后的配置
      return {
        roleType: 'all' as unknown as RoleType,
        specificDate: date,
        dateType: hasCloseAllDay ? DateType.CLOSE_ALL_DAY : DateType.CUSTOM_TIME_SLOTS,
        timeslots: hasCloseAllDay ? [] : allTimeslots,
        // 标记包含默认和特定时间段
        isDefaultOnly: false,
        defaultTimeslotsCount: defaultTimeslots.length
      };
    }
    return specificDates.find(sd => sd.specificDate === date && sd.roleType === displayFor);
  };

  // // 删除特定日期配置
  // const handleDeleteSpecificDate = (date: string) => {
  //   const updatedSpecificDates = specificDates.filter(
  //     sd => !(sd.specificDate === date && sd.roleType === safeDisplayFor)
  //   );
  //   setSpecificDates(updatedSpecificDates);
  //   onSpecificDateChange?.(updatedSpecificDates);
  //   // 不要重置选中状态，保持用户的选择
  // };

  // // 更新日期类型（开关状态）
  // const handleDateTypeChange = (date: string, enabled: boolean) => {
  //   const updatedSpecificDates = [...specificDates];
  //   const existingIndex = updatedSpecificDates.findIndex(
  //     sd => sd.specificDate === date && sd.roleType === safeDisplayFor
  //   );

  //   if (existingIndex >= 0) {
  //     // 更新现有配置
  //     updatedSpecificDates[existingIndex].dateType = enabled ? DateType.CUSTOM_TIME_SLOTS : DateType.CLOSE_ALL_DAY;
  //   } else {
  //     // 创建新配置
  //     const defaultTimeslots = generateDefaultTimeslots(date);
  //     updatedSpecificDates.push({
  //       roleType: safeDisplayFor,
  //       specificDate: date,
  //       dateType: enabled ? DateType.CUSTOM_TIME_SLOTS : DateType.CLOSE_ALL_DAY,
  //       timeslots: enabled ? convertToSpecificTimeslots(defaultTimeslots) : []
  //     });
  //   }

  //   setSpecificDates(updatedSpecificDates);
  //   onSpecificDateChange?.(updatedSpecificDates);
  // };

  // // 添加时间段
  // const handleAddTimeslot = (date: string) => {
  //   const updatedSpecificDates = [...specificDates];
  //   const index = updatedSpecificDates.findIndex(
  //     sd => sd.specificDate === date && sd.roleType === safeDisplayFor
  //   );

  //   if (index >= 0) {
  //     // 更新现有特定配置
  //     updatedSpecificDates[index].timeslots.push({
  //       startTime: '09:00:00',
  //       endTime: '17:00:00'
  //     });
  //   } else {
  //     // 创建新的特定配置，基于默认配置
  //     const defaultTimeslots = generateDefaultTimeslots(date);
  //     updatedSpecificDates.push({
  //       roleType: safeDisplayFor,
  //       specificDate: date,
  //       dateType: DateType.CUSTOM_TIME_SLOTS,
  //       timeslots: [
  //         ...convertToSpecificTimeslots(defaultTimeslots),
  //         {
  //           startTime: '09:00:00',
  //           endTime: '17:00:00'
  //         }
  //       ]
  //     });
  //   }

  //   setSpecificDates(updatedSpecificDates);
  //   onSpecificDateChange?.(updatedSpecificDates);
  // };

  // 时间字符串转分钟数（特定日期用）
  const timeStringToMinutesSpecific = (timeStr: string): number => {
    const [hours, minutes] = timeStr.split(':').map(Number);
    return hours * 60 + minutes;
  };

  // 校验时间段是否符合最小间隔要求（特定日期用）
  const validateTimeSlotIntervalSpecific = (startTime: string, endTime: string): boolean => {
    const startMinutes = timeStringToMinutesSpecific(startTime);
    const endMinutes = timeStringToMinutesSpecific(endTime);
    const duration = endMinutes - startMinutes;

    // 检查时长是否满足最小要求
    if (duration < minDuration) {
      message.error(`时间段长度不能少于${minDuration}分钟`);
      return false;
    }

    // 如果设置了30分钟最小间隔，检查时间点是否符合要求
    if (minDuration >= 30) {
      // 检查开始时间是否为30分钟的倍数
      if (startMinutes % 30 !== 0) {
        const nextValidStart = Math.ceil(startMinutes / 30) * 30;
        const nextValidStartHour = Math.floor(nextValidStart / 60);
        const nextValidStartMin = nextValidStart % 60;
        const nextValidStartTime = `${nextValidStartHour.toString().padStart(2, '0')}:${nextValidStartMin.toString().padStart(2, '0')}`;
        message.error(`开始时间必须为30分钟的倍数，建议调整为${nextValidStartTime}`);
        return false;
      }

      // 检查结束时间是否为30分钟的倍数
      if (endMinutes % 30 !== 0) {
        const nextValidEnd = Math.ceil(endMinutes / 30) * 30;
        const nextValidEndHour = Math.floor(nextValidEnd / 60);
        const nextValidEndMin = nextValidEnd % 60;
        const nextValidEndTime = `${nextValidEndHour.toString().padStart(2, '0')}:${nextValidEndMin.toString().padStart(2, '0')}`;
        message.error(`结束时间必须为30分钟的倍数，建议调整为${nextValidEndTime}`);
        return false;
      }

      // 检查时长是否为30分钟的倍数
      if (duration % 30 !== 0) {
        message.error(`时间段长度必须为30分钟的倍数`);
        return false;
      }
    }

    return true;
  };

  // 更新时间段
  const handleUpdateTimeslot = (date: string, timeslotIndex: number, field: string, value: string) => {
    const updatedSpecificDates = [...specificDates];
    const index = updatedSpecificDates.findIndex(
      sd => sd.specificDate === date && (displayFor === 'all' ? sd.roleType === RoleType.LEVEL_1_USER : sd.roleType === displayFor)
    );

    if (index >= 0) {
      const currentTimeslot = updatedSpecificDates[index].timeslots[timeslotIndex];
      const newTimeslot = {
        ...currentTimeslot,
        [field]: value
      };

      // 校验时间段
      if (!validateTimeSlotIntervalSpecific(newTimeslot.startTime, newTimeslot.endTime)) {
        return; // 校验失败，不更新
      }

      updatedSpecificDates[index].timeslots[timeslotIndex] = newTimeslot;
      setSpecificDates(updatedSpecificDates);
      onSpecificDateChange?.(updatedSpecificDates);
    }
  };

  // 删除时间段
  const handleDeleteTimeslot = (date: string, timeslotIndex: number) => {
    const updatedSpecificDates = [...specificDates];
    const index = updatedSpecificDates.findIndex(
      sd => sd.specificDate === date && (displayFor === 'all' ? sd.roleType === RoleType.LEVEL_1_USER : sd.roleType === displayFor)
    );

    if (index >= 0) {
      updatedSpecificDates[index].timeslots.splice(timeslotIndex, 1);
      setSpecificDates(updatedSpecificDates);
      onSpecificDateChange?.(updatedSpecificDates);
    }
  };

  return (
    <div>
      {/* 顶部控制栏 */}
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center',
        marginBottom: 16
      }}>
        <Button 
          type="text" 
          icon={<LeftOutlined />} 
          onClick={handlePrevWeek}
        />
        
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <Text strong>
            {currentWeek.format('YYYY年MM月')}
          </Text>
          <Space>
            <Text>用户级别：</Text>
            <Select 
              value={displayFor}
              onChange={onDisplayChange}
              style={{ width: 120 }}
            >
              {userLevelOptions.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Space>
          {/* <Space>
            <Text>视图模式：</Text>
            <Select 
              value={currentViewMode}
              onChange={setCurrentViewMode}
              style={{ width: 120 }}
              disabled={readOnly}
            >
              <Option value={ViewMode.CARD}>卡片模式</Option>
              <Option value={ViewMode.CALENDAR}>日历模式</Option>
            </Select>
          </Space> */}
        </div>
        
        <Button 
          type="text" 
          icon={<RightOutlined />} 
          onClick={handleNextWeek}
          disabled={readOnly}
        />
      </div>

      {/* 视图内容 */}
      {viewMode === ViewMode.CARD ? (
        <CardView 
          weekDates={weekDates}
          dayStatusMap={dayStatusMap}
          selectedDate={selectedDate}
          setSelectedDate={setSelectedDate}
          getSpecificDateConfig={getSpecificDateConfig}
          generateDefaultTimeslots={generateDefaultTimeslots}
          readOnly={readOnly}
        />
      ) : (
        <CalendarView 
          weekDates={weekDates}
          dayStatusMap={dayStatusMap}
          getSpecificDateConfig={getSpecificDateConfig}
          generateDefaultTimeslots={generateDefaultTimeslots}
          minDuration={minDuration}
          readOnly={readOnly}
          selectedDate={selectedDate}
          setSelectedDate={setSelectedDate}
          onSpecificDateChange={onSpecificDateChange}
          specificDates={specificDates}
          displayFor={displayFor}
          convertToSpecificTimeslots={convertToSpecificTimeslots}
        />
      )}

      {/* {selectedDate && (
        <Card title={`配置 ${selectedDate} 的可预约时间`}>
          {(() => {
            const specificConfig = getSpecificDateConfig(selectedDate);
            const dayStatus = dayStatusMap.get(selectedDate);
            const defaultTimeslots = generateDefaultTimeslots(selectedDate);
            
            return (
              <div>
                <div style={{ marginBottom: 16, padding: 12, backgroundColor: '#f5f5f5', borderRadius: 6 }}>
                  <Space>
                    <Text strong>日期状态：</Text>
                    {dayStatus && (
                      <Tag color={
                        dayStatus.scheduleType === ScheduleType.HOLIDAY ? 'red' : 
                        dayStatus.scheduleType === ScheduleType.WORKDAY ? 'blue' : 'purple'
                      }>
                        {dayStatus.scheduleType === ScheduleType.HOLIDAY ? '节假日' : 
                         dayStatus.scheduleType === ScheduleType.WORKDAY ? '工作日' : '周末'}
                      </Tag>
                    )}
                    <Text strong>是否工作日：</Text>
                    <Tag color={dayStatus?.isWorkday ? 'green' : 'default'}>
                      {dayStatus?.isWorkday ? '是' : '否'}
                    </Tag>
                  </Space>
                </div>

                <Card 
                  type="inner" 
                  title={
                    <Space>
                      <Text strong>默认可预约时间</Text>
                      <Tag color="green">
                        {displayFor === 'all' ? '所有用户' : userLevelOptions.find(o => o.value === displayFor)?.label}
                      </Tag>
                    </Space>
                  }
                  style={{ marginBottom: 16 }}
                  size="small"
                >
                  {defaultTimeslots.length > 0 ? (
                    <div>
                      {defaultTimeslots.map((timeslot, index) => (
                        <div key={index} style={{ 
                          display: 'flex', 
                          alignItems: 'center', 
                          gap: 8, 
                          marginBottom: 8,
                          padding: '4px 8px',
                          backgroundColor: '#f9f9f9',
                          borderRadius: 4
                        }}>
                          <Text>{timeslot.startTime.substring(0, 5)}</Text>
                          <Text type="secondary">至</Text>
                          <Text>{timeslot.endTime.substring(0, 5)}</Text>
                          <Text type="secondary">（默认配置）</Text>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <Text type="secondary">该日期无默认配置</Text>
                  )}
                </Card>

                <Card 
                  type="inner" 
                  title="特定日期配置"
                  style={{ marginBottom: 16 }}
                  size="small"
                >
                  <div style={{ marginBottom: 16 }}>
                    <Text strong style={{ marginRight: 16 }}>配置类型：</Text>
                    <Radio.Group 
                      value={specificConfig ? specificConfig.dateType : 'default'}
                      onChange={(e) => {
                        const newValue = e.target.value;
                        if (newValue === 'default') {
                          // 移除特定配置，使用默认配置
                          handleDeleteSpecificDate(selectedDate);
                        } else if (newValue === DateType.CLOSE_ALL_DAY) {
                          // 创建关闭整天的特定配置
                          handleDateTypeChange(selectedDate, false);
                        } else if (newValue === DateType.CUSTOM_TIME_SLOTS) {
                          // 创建自定义时间段的特定配置
                          handleDateTypeChange(selectedDate, true);
                        }
                      }}
                      disabled={readOnly}
                    >
                      <Radio value="default">使用默认配置</Radio>
                      <Radio value={DateType.CLOSE_ALL_DAY}>关闭整天</Radio>
                      <Radio value={DateType.CUSTOM_TIME_SLOTS}>自定义时间段</Radio>
                    </Radio.Group>
                  </div>

                  {!specificConfig && (
                    <div style={{ marginBottom: 16, padding: 12, backgroundColor: '#f0f8ff', borderRadius: 4 }}>
                      <Text type="secondary">当前使用默认配置，该日期的可预约时间将遵循上方显示的默认时间安排</Text>
                    </div>
                  )}

                  {specificConfig && specificConfig.dateType === DateType.CUSTOM_TIME_SLOTS && (
                    <div>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
                        <Text strong>时间段设置</Text>
                        <Space>
                          {!readOnly && (
                            <Button 
                              type="dashed" 
                              size="small"
                              icon={<PlusOutlined />}
                              onClick={() => handleAddTimeslot(selectedDate)}
                            >
                              添加时间段
                            </Button>
                          )}
                          {!readOnly && specificConfig && (
                            <Button 
                              type="text" 
                              size="small"
                              danger
                              onClick={() => handleDeleteSpecificDate(selectedDate)}
                            >
                              清除特定配置
                            </Button>
                          )}
                        </Space>
                      </div>

                      {specificConfig && specificConfig.timeslots.length > 0 ? (
                        specificConfig.timeslots.map((timeslot, index) => (
                          <div key={index} style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                            <TimePicker
                              value={timeslot.startTime ? dayjs(timeslot.startTime, 'HH:mm:ss') : null}
                              format="HH:mm"
                              placeholder="开始时间"
                              disabled={readOnly}
                              minuteStep={getMinuteStep()}
                              onChange={(time) =>
                                handleUpdateTimeslot(selectedDate, index, 'startTime', time ? time.format('HH:mm:ss') : '09:00:00')
                              }
                            />
                            <Text>至</Text>
                            <TimePicker
                              value={timeslot.endTime ? dayjs(timeslot.endTime, 'HH:mm:ss') : null}
                              format="HH:mm"
                              placeholder="结束时间"
                              disabled={readOnly}
                              minuteStep={getMinuteStep()}
                              onChange={(time) =>
                                handleUpdateTimeslot(selectedDate, index, 'endTime', time ? time.format('HH:mm:ss') : '17:00:00')
                              }
                            />
                            {!readOnly && (
                              <Button 
                                type="link" 
                                size="small"
                                icon={<DeleteOutlined />}
                                onClick={() => handleDeleteTimeslot(selectedDate, index)}
                              >
                                删除
                              </Button>
                            )}
                          </div>
                        ))
                      ) : (
                        <div style={{ textAlign: 'center', padding: 24, color: '#999', backgroundColor: '#fafafa', borderRadius: 4 }}>
                          <Text type="secondary">暂无自定义时间段，点击&quot;添加时间段&quot;开始配置</Text>
                        </div>
                      )}
                    </div>
                  )}

                  {specificConfig && specificConfig.dateType === DateType.CLOSE_ALL_DAY && (
                    <div style={{ textAlign: 'center', padding: 24, color: '#999', backgroundColor: '#fff2e8', borderRadius: 4 }}>
                      <Text type="secondary">该日期已设置为关闭整天，不可预约</Text>
                    </div>
                  )}
                </Card>

                <Card 
                  type="inner" 
                  title="当前生效配置"
                  size="small"
                >
                  <Space direction="vertical" style={{ width: '100%' }}>
                    <div>
                      <Text strong>配置来源：</Text>
                      <Tag color={specificConfig ? 'blue' : 'green'}>
                        {specificConfig ? '特定日期配置' : '默认配置'}
                      </Tag>
                    </div>
                    
                    <div>
                      <Text strong>预约状态：</Text>
                      <Tag color={
                        specificConfig 
                          ? (specificConfig.dateType === DateType.CUSTOM_TIME_SLOTS ? 'success' : 'error')
                          : (defaultTimeslots.length > 0 ? 'success' : 'default')
                      }>
                        {specificConfig 
                          ? (specificConfig.dateType === DateType.CUSTOM_TIME_SLOTS ? '可预约' : '关闭整天')
                          : (defaultTimeslots.length > 0 ? '可预约' : '无配置')
                        }
                      </Tag>
                    </div>
                    
                    <div>
                      <Text strong>可预约时间段：</Text>
                      <Text>
                        {(() => {
                          if (specificConfig) {
                            if (specificConfig.dateType === DateType.CLOSE_ALL_DAY) {
                              return '无（关闭整天）';
                            } else {
                              return specificConfig.timeslots.length > 0 
                                ? `${specificConfig.timeslots.length} 个时间段`
                                : '无时间段';
                            }
                          } else {
                            return defaultTimeslots.length > 0 
                              ? `${defaultTimeslots.length} 个时间段（默认配置）`
                              : '无配置';
                          }
                        })()}
                      </Text>
                    </div>
                  </Space>
                </Card>
              </div>
            );
          })()}
        </Card>
      )} */}
{/* 
      {!selectedDate && (
        <div style={{ textAlign: 'center', padding: 32, color: '#999' }}>
          <Text type="secondary">请点击上方日期开始配置特定日期的可预约时间</Text>
        </div>
      )} */}
    </div>
  );
};

export default WeeklyTimeSelector; 